﻿using PagedList;
using PagedList.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GiaoTrinhEPU.Repositories.Repositories;
using GiaoTrinhEPU.Repositories.DataModels;
using GiaoTrinhEPU.Repositories;
using GiaoTrinhEPU.Repositories.Interfaces;
using GiaoTrinhEPU.Core.ActionResults;
using GiaoTrinhEPU.Core;

namespace GiaoTrinhEPU.Areas.Manager.Controllers
{
    public class AuthorController : BaseController
    {
        /// <summary>
        /// Declare Author Repository
        /// </summary>
        private AuthorRepository authorRepository;
        
        /// <summary>
        ///  Declare Session
        /// </summary>
        public static string SessionAuthorSort = "SessionAuthorSort";
        public static string SessionAuthorSearch = "SessionAuthorSearch";
        public static string SessionAuthorSortOpt = "SessionAuthorSortOpt";



        // GET: /Author/
        /// <summary>
        /// Constructor that allow to create a Comment controller
        /// </summary>
        public AuthorController()
            : base()
        {
            this.authorRepository = new AuthorRepository();
            ViewBag.SelectedMenuId = 25;
            
        }

        public ActionResult Index(int page = 1, int size = 25, String search = "", String opt = "", String sort = "")
        {
            ViewBag.Title = "Tác Giả";
            // Stored Session
            Session[SessionAuthorSort] = sort.Trim().Length > 0 ? sort.ToLower() : Session[SessionAuthorSort];
            Session[SessionAuthorSortOpt] = opt.Trim().Length > 0 ? opt.ToLower() : Session[SessionAuthorSortOpt];

            var author = this.authorRepository.ListAuthors(false).ToList();

            // Sort 
            ViewBag.SortNameOpt = "desc";
            if (Session[SessionAuthorSort] != null)
            {
                switch (Session[SessionAuthorSort].ToString())
                {
                    case "name":
                        author = Session[SessionAuthorSortOpt].ToString().Equals("desc") ? author.OrderByDescending(s => s.Name).ToList() : author.OrderBy(s => s.Name).ToList();

                        Session[SessionAuthorSort] = "name";
                        ViewBag.SortNameOpt = Sort.SetSortOrderOption(Session[SessionAuthorSortOpt].ToString());
                        break;

                    default:
                        break;
                }
            }


            return View(author.ToPagedList(page, size));
        }
        /// <summary>
        /// Get
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Create()
        {
            var authorModel = new AuthorModel();

            this.PopulateDepartmentDropDownList(authorModel.DepartmentId);
            return View(authorModel);
        }
        /// <summary>
        /// create action with param
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(AuthorModel model)
        {
            ViewBag.EnabledMenu = false;

            if (!ModelState.IsValid)
            {
                return View("Create");
            }
            else
            {
                if (this.authorRepository.HasNameExisted(model.Name) == true)
                {
                    return View("Create").WithErrorMessage("Tên tác giả đã được sử dụng");
                }


                var author = new Author();
                author.Id = (int)model.Id;
                author.Name = model.Name;
                author.DepartmentId = model.DepartmentId;
                author.Description = model.Description;

                this.authorRepository.CreateAuthor(author);
                // Returns view with successful message
                return RedirectToAction("Index").WithSuccessMessage("Đã tạo thành công tác giả mới"); ;
            }
        }
        /// <summary>
        ///  Edit action 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Edit(int id = 0)
        {
            ViewBag.EnabledMenu = false;

            var author = this.authorRepository.GetAuthorById(id);
            var authorModel = new AuthorModel(author);

            this.PopulateDepartmentDropDownList(authorModel.DepartmentId);


            return View(authorModel);
        }
        /// <summary>
        ///  Edit action 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(AuthorModel model)
        {
            ViewBag.EnabledMenu = false;

            if (!ModelState.IsValid)
            {
                return View("Edit");
            }
            else
            {
                if (this.authorRepository.HasNameDuplicated(model.Id, model.Name) == true)
                {
                    return View("Edit").WithErrorMessage("Tên tác giả đã được sử dụng");
                }

                var author = new Author();

                author.Id = (int)model.Id;
                author.Name = model.Name;
                author.DepartmentId = model.DepartmentId;
                author.Description = model.Description;

                this.authorRepository.UpdateAuthor(author);

                return RedirectToAction("Index").WithSuccessMessage("Đã sửa thành công tác giả này");

            }
        }
        /// <summary>
        /// Delete action 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Delete(int id)
        {
            this.authorRepository.DeleteAuthor(id);
            return RedirectToAction("Index").WithSuccessMessage("Đã xóa thành công tác giả này"); ;
        }

        /// <summary>
        ///  Delete Multi
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DeleteMulti(int[] ids = null)
        {
            if (ids == null || ids.Length == 0)
            {
                return RedirectToAction("Index");
            }

            for (int i = 0; i < ids.Length; i++)
            {
                int id = ids[i];

                this.authorRepository.DeleteAuthor(id);
            }

            return RedirectToAction("Index").WithSuccessMessage("Đã xóa thành công những tác giả này");
        }
        /// <summary>
        /// Clear
        /// </summary>
        /// <returns></returns>
        public ActionResult Clear()
        {
            // Clear sessions
            Session[SessionAuthorSearch] = null;
            Session[SessionAuthorSort] = null;
            Session[SessionAuthorSortOpt] = null;

            return RedirectToAction("Index");
        }
        /// <summary>
        /// check name avaiable
        /// </summary>
        /// <param name="name"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public JsonResult IsNameAvaiable(String name, int Id = 0)
        {
            if (Id == 0)
            {
                if (!this.authorRepository.HasNameExisted(name))
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                if (!this.authorRepository.HasNameDuplicated(Id, name))
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }


            }

            return Json("Tên tác giả đã được sử dụng", JsonRequestBehavior.AllowGet);
        }
    }
}
